var TimerBookmarklet = function () {
    
    jQuery.noConflict();
    
    function init() {
    
        if(jQuery('#me_productive_timerbookmarklet').length === 1) {
            jQuery('#me_productive_timerbookmarklet').remove();
        } else {
        
            // -- create dom
            
            var $container = jQuery('<div id="me_productive_timerbookmarklet" />');
            var $sectionContainer = jQuery('<div />');
            var $minutesContainer = jQuery('<div />');
            var $minutes = jQuery('<input type="text" placeholder="? min" />');
            var $minutesL = jQuery('<div />');
            var $add = jQuery('<div>+</div>');
            var $progress = jQuery('<div />');
            var $addTitle = jQuery('<input type="text" placeholder="Section Name" />');
            var $section0 = jQuery('<div class="ti_section" />');
            
            var sections = new Array();
            sections[0] = "...";
            var sectionEdit = -1;
            
            jQuery("body").append($container
                            .append($sectionContainer
                                   .append($progress)
                                   .append($addTitle))
                            .append($add)
                            .append($minutesContainer
                                   .append($minutesL)
                                   .append($minutes)));
            
            // -- apply styles
            
            $container.css({
                'font-size':'1.1em',
                'font-family':'"Trebuchet MS",Verdana,Arial',
                color:'#333',
                border:'1px solid #333',
                background:'white',
                opacity:0.6,
                position:'absolute',
                top:0,
                right:0,
                margin:'1em',
                padding:'1em',
                'z-index':99999997,
                width:'21em',
                height:'1.5em' 
            }).draggable();
            
            $sectionContainer.css({
                float:'left',
                width:'16em',
                height:'1.3em',
                position:'relative'
            });
            
            $minutesContainer.css({
                float:'left',
                width:'4em',
                height:'1.3em',
                position:'relative'
            });
            
            $minutesL.css({
                width:'100%',
                height:'100%',
                cursor:'pointer',
                'text-align':'center'
            });
            
            $minutes.css({
                width:'100%',
                height:'100%',
                position:'absolute',
                left:0,
                top:0,
                border:'1px solid #888',
                background:'white',
                'text-align':'center',
                'font-size':'1em'
            });
            
            $add.css({
                float:'left',
                cursor:'pointer',            
                padding: '0em 0.3em 0em 0.1em',
                height:'100%'
            });
            
            $addTitle.css({
                width:'100%',
                height:'100%',
                position:'absolute',
                left:0,
                top:0,
                border:'1px solid #888',
                'background-color':'#FFF',
                'text-align':'center',
                'font-size':'1em',
                'z-index':2
            }).hide();
            
            $section0.css({
                border:'1px solid #888',
                float:'left',
                height:'100%',
                width:'1px',
                position:'relative',
                'white-space': 'nowrap', 
                background:'transparent',
                overflow: 'hidden',
                'text-overflow': 'ellipsis',
                'text-align':'center',
                cursor:'pointer'
            });
            
            $progress.css({
                position:'absolute',
                width:0,
                height:'1.3em',
                left:0,
                border: '1px solid transparent'
            });
            
           
            // -- hook events
            
            $minutes
                .change(applyMinutes)
                .keyup(function(e){
                    if(e.which === 13 || e.which === 9) applyMinutes();
                });
                
            $minutesL.click(function() {
                $minutesL.hide();
                $minutes.show().focus().select();
            }); 
            
            $add.click(function() {
                sections[sections.length] = "...";
            });
            
            $addTitle
                .change(addSection)
                .keyup(function(e) {
                    if(e.which === 13 || e.which === 9) {
                        addSection();
                    }
                });
        
            // -- functions
            
            function applyMinutes() {
                $minutesL.text($minutes.val() + ' min');
                endtime = null;
                if($minutes.val() !== '') {
                    $minutes.hide();
                    $minutesL.show();
                }
            }
                   
            function addSection() {
                if($addTitle.val() !== '') {
                    __log(sectionEdit + ' == -1?');
                    if(sectionEdit === -1) {
                        __log('yes');
                        sections[sections.length] = $addTitle.val();
                    } else {
                        __log('no');
                        sections[sectionEdit] = $addTitle.val();
                        sectionEdit = -2;
                    }
                    $addTitle.val("");
                    $addTitle.hide();
                }
            }  
            
            function setCookie() {
                jQuery.cookie('me_productive_timerbookmarklet',sections.join(';') + "|" + $minutes.val() +"|" + endtime.getUTCFullYear() + ','+ endtime.getUTCMonth() + ','+ endtime.getUTCDate() + ','+ endtime.getUTCHours() + ','+ endtime.getUTCMinutes() + ','+ endtime.getUTCSeconds(), {
                            expires: endtime,
                            path: '/'
                        });
            }
            
            // -- controller
            
            var endtime = null;
            var starttime = null;
            var remaining = -1;
            
            function timer() {
                if(sections.length > 0) {
                    if($minutes.val() !== "" && endtime === null) {
                        starttime = new Date();
                        endtime = new Date(starttime.getTime() + $minutes.val()*60000);
                        setCookie();
                    }
                    if(endtime !== null) {
                        __log(endtime.getHours() +':'+endtime.getMinutes());
                        remaining = (endtime.getTime() - new Date().getTime())/60000;
                        __log('remaining ' + remaining);
                        $minutesL.text(Math.ceil(remaining) + " min");
                        if(remaining >= 0) {
                            
                            var sectionPerc = (((new Date().getTime() - starttime.getTime())/60000) % ($minutes.val()/sections.length)) / ($minutes.val()/sections.length);
                            $progress.css({
                                width:($minutes.val() - remaining)*98/$minutes.val() + '%',
                                background: (sectionPerc > 0.9 ? '#FF6464' : sectionPerc > 0.75 ? '#FFB164' : '#64FF64')
                            });
                               
                            __log('width ' + ($minutes.val() - remaining)*98/$minutes.val());
                        } else {
                            $progress.css({
                                width:'98%',
                                background: '#64FF64' 
                            });
                        }
                    }
                }
                __log(sectionEdit + ' == -2?');
                if(sections.length != $sectionContainer.find('.ti_section').length || sectionEdit === -2) {
                    if(endtime !== null) setCookie();
                    $sectionContainer.find('.ti_section').remove();
                    for(var i=0;i<sections.length;i++){
                        $section0.clone(true)
                            .css({
                                width:98/sections.length +'%',
                                'border-left':(i == 0 ? '1px solid #333' : 'none')
                            }).attr('id','me_productive_timerbookmarklet_ti_section_' + i)
                            .text(sections[i])
                            .click(function() {
                                __log("Edit clicked");
                                sectionEdit = jQuery(this).attr('id').replace('me_productive_timerbookmarklet_ti_section_','');
                                __log(sectionEdit);
                               $addTitle.val(jQuery(this).text());
                               $addTitle.show().focus().select();
                            })
                            .appendTo($sectionContainer);
                    }
                    sectionEdit = -1;
                }
                
                setTimeout(timer,2000);
            }
            
            if(jQuery.cookie('me_productive_timerbookmarklet') !== null) {
               var cookieParts = jQuery.cookie('me_productive_timerbookmarklet').split('|');
               sections = cookieParts[0].split(';');
              $minutes.val(cookieParts[1]);
               applyMinutes();
               endtime = eval('new Date(Date.UTC(' + cookieParts[2] + '))'); 
               starttime = new Date(endtime.getTime() - $minutes.val()*60000);
            }
            
            setTimeout(timer,0);
            
        }

        // -- Debugger
        
        function __log(message) {}
    
        /* Uncomment to activate debugger
        var $debug = jQuery('<div />');
        $container.append($debug);
        
        $debug.css({
            'font-size':'0.8em',
            'max-height':'6em',
            background:'white',
            overflow:'auto',
            position:'absolute',
            width:'100%',
            top:'5em',
            left:0
        });
            
        function __log(message) {
            if($debug.is(':visible')) {
               $debug.prepend(jQuery('<span />').text(message).after(jQuery("<br />")));
            }
        }
        
        $debug.show();
        //*/ 
    }

    return {
        show: function() {
            init();
        }
    }
    
}();